package com.base.cn.platform.os.controller.web.user.login;

import com.base.cn.platform.os.common.WebBaseController;
import com.base.cn.platform.os.common.constants.CommonConstants;
import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.rsa.WebRsaUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.user.LoginForm;
import com.base.cn.platform.os.common.utils.user.UserExpandFrom;
import com.base.cn.platform.os.common.utils.web.WebUtils;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.manage.op.advert.OpAdvertService;
import com.base.cn.platform.os.service.manage.user.login.UserLoginService;
import com.base.cn.platform.os.service.manage.user.sms.UserSendSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 前台登录Controller
 *
 * @author s.li
 * @create 2018-05-10-19:40
 */
@Controller
@RequestMapping("/web/user")
public class WebLoginController extends WebBaseController {
    @Autowired
    private UserLoginService userLoginService;
    @Autowired
    private UserSendSmsService userSendSmsService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private LoginUserData loginUserData;
    @Autowired
    private OpAdvertService opAdvertService;
    @Autowired
    private CustomCacheChannel customCacheChannel;

    /**
     * 用户注册协议
     * @return
     */
    @RequestMapping("/protocol")
    public String regUserProtocol(Model model){
        TreeMap<String,String> configMap = sysConfigService.getSysConfigContext(ConfigName.PROTOCOL);
        model.addAttribute("configMap",configMap);
        return resultPage("/user/protocol/reg-user-protocol");
    }

    /**
     * 判断用户是否登录
     * @param request
     */
    @RequestMapping("/isLogin")
    @ResponseBody
    public Map<String, Object> isLogin(HttpServletRequest request,
                                       HttpServletResponse response){
        boolean isLogin = webMobileLoginUtil.isLogin(request);
        if(isLogin==false){//如果未登录，则缓存当前页面的url
            String requestURL = request.getHeader("referer");
            WebUtils.setCookie(response,CommonConstants.REDIRECT,requestURL,1);
        }
        return ResultUtil.SUCCESS(isLogin);
    }

    /**
     * 跳转登录页面
     *
     * @return 登录/注册页面
     */
    @RequestMapping("/login")
    public String login(@RequestParam(value = "message",required = false) String message,
                        Model model) throws Exception {
        setAdvertList(model);
        TreeMap<String, String> sysConfigContext = sysConfigService.getSysConfigContext(ConfigName.ONOFF);
        String weiXinLoginSwitch = sysConfigContext.get("weiXinLoginSwitch");
        String qqLoginSwitch = sysConfigContext.get("qqLoginSwitch");
        model.addAttribute("weiXinLoginSwitch",weiXinLoginSwitch);
        model.addAttribute("qqLoginSwitch",qqLoginSwitch);
        Map<String,String> keyMap = WebRsaUtils.getRSAData(customCacheChannel);
        model.addAttribute("keyMap",keyMap);
        model.addAttribute("message",message);
        return resultPage("/user/login/phase-login");
    }

    /**
     * 自动跳转登录页面
     * @return
     */
    @RequestMapping("/autoToLoginPage")
    public String autoToLoginPage(){
        return resultPage("/user/login/auto-login-page");
    }

    /**
     * 跳转注页面
     *
     * @return 登录/注册页面
     */
    @RequestMapping("/register")
    public String register(Model model) throws Exception{
        setAdvertList(model);
        Map<String,String> keyMap = WebRsaUtils.getRSAData(customCacheChannel);
        model.addAttribute("keyMap",keyMap);
        return resultPage("/user/login/phase-register");
    }

    /**
     * PC登录 --- 滑动拼图验证码方式
     *
     * @param request HttpServletRequest
     * @param moveLeft  自动登录
     * @param gapLeft 验证码参数
     * @param moveLeft 验证码参数
     * @param password 密码
     * @param loginAccount 帐号
     * @return Map<String,Object>
     */
    @RequestMapping("/doLogin")
    @ResponseBody
    public Map<String, Object> doLogin(HttpServletRequest request, HttpServletResponse response,
                                       @RequestParam("autoThirty")String autoThirty,
                                       @RequestParam("loginAccount")String loginAccount,
                                       @RequestParam("password")String password,
                                       @RequestParam("gapLeft") String gapLeft,
                                       @RequestParam("moveLeft") String moveLeft,
                                       @RequestParam("sign") String sign) throws Exception{
        Map<String,Object> params=new HashMap<>();
        params.put("loginAccount",loginAccount);
        params.put("password",password);
        params.put("sign",sign);
        Map<String,Object> resultMap = userLoginService.userLogin(params, LoginForm.LOGIN_FROM_PC,autoThirty, gapLeft,moveLeft);
        resultMap = loginUserData.setUserData(request,response,resultMap,autoThirty);
        if(!ResultUtil.getSuccess(resultMap)){//如果登录失败，则重新获取密钥
            Map<String,String> keyMap = WebRsaUtils.getRSAData(customCacheChannel);
            resultMap.put("keyMap",keyMap);
        }
        return resultMap;
    }

    /**
     * 注册用户
     *
     * @param request HttpServletRequest
     * @param mobile  手机号
     * @param mobileCode  手机验证码
     * @param password  密码
     * @param confirmPwd  确认密码
     */
    @RequestMapping("/doRegister")
    @ResponseBody
    public Map<String, Object> doRegister(HttpServletRequest request, HttpServletResponse response,
                                          @RequestParam("mobile")String mobile,
                                          @RequestParam("mobileCode")String mobileCode,
                                          @RequestParam("password")String password,
                                          @RequestParam("confirmPwd")String confirmPwd,
                                          @RequestParam("sign") String sign)throws Exception {
        Map<String,Object> user = new HashMap<>();
        user.put("mobile",mobile);
        user.put("mobileCode",mobileCode);
        user.put("password",password);
        user.put("confirmPwd",confirmPwd);
        user.put("registerFrom", UserExpandFrom.registerFrom.getKey());
        user.put("sign", sign);
        Map<String,Object> resultMap =userLoginService.toRegister(user,LoginForm.LOGIN_FROM_PC);
        resultMap = loginUserData.setUserData(request,response,resultMap,"false");
        if(!ResultUtil.getSuccess(resultMap)){//如果登录失败，则重新获取密钥
            Map<String,String> keyMap = WebRsaUtils.getRSAData(customCacheChannel);
            resultMap.put("keyMap",keyMap);
        }
        return resultMap;
    }

    /**
     * 退出登录
     * @param request HttpServletRequest
     * @return 跳转页面
     */
    @RequestMapping("/signOut")
    public String signOut(HttpServletRequest request, HttpServletResponse response) {
        String sessionId = WebUtils.getCookie(request,CommonConstants.USER_SINGLE_ID);
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        boolean isOk = userLoginService.signOut(sessionId,userId);
        if(isOk){//删除COOKIE会话
            WebUtils.deleteCookie(request,response,CommonConstants.USER_SINGLE_ID);
        }
        return redirect(request,"/web/index");
    }

    //======================================完善用户资料，开始============================

    /**
     * 设置学员专业
     * @param sessionId 用户缓存KEY
     * @param parentId 专业ID
     * @param childIds 科目ID串
     * @param autoThirty 缓存30天
     * @return Map<String,Object>
     */
    @RequestMapping("/setUserSubjectIds")
    @ResponseBody
    public Map<String,Object> setUserSubjectIds(HttpServletRequest request,HttpServletResponse response,
                                                @RequestParam("sessionId") String sessionId,
                                                @RequestParam("parentId") BigDecimal parentId,
                                                @RequestParam("childIds") String childIds,
                                                @RequestParam("autoThirty") String autoThirty){
        Map<String,Object> resultMap = userLoginService.setUserSubjectIds(sessionId,parentId,childIds,autoThirty,LoginForm.LOGIN_FROM_PC);
        return  loginUserData.setUserData(request,response,resultMap,autoThirty);
    }

    /**
     * 设置用户手机号
     * @param sessionId 缓存KEY
     * @param mobile 手机号
     * @param mobileCode 手机验证码
     * @param autoThirty 缓存30天
     * @return Map<String,Object>
     */
    @RequestMapping("/setUserMobile")
    @ResponseBody
    public Map<String,Object> setUserMobile(HttpServletRequest request,HttpServletResponse response,
                                            @RequestParam("sessionId") String sessionId,
                                            @RequestParam("mobile") String mobile,
                                            @RequestParam("mobileCode") String mobileCode,
                                            @RequestParam("autoThirty") String autoThirty){
        Map<String,Object> resultMap = userLoginService.setUserMobile(sessionId,mobile,mobileCode,autoThirty,LoginForm.LOGIN_FROM_PC);
        return  loginUserData.setUserData(request,response,resultMap,autoThirty);
    }
    //======================================完善用户资料，结束============================

    //=============================找回密码，开始================================
    /**
     * 找回密码页面
     * @return
     */
    @RequestMapping("/retrievePage")
    public String retrievePage(Model model) throws Exception{
        setAdvertList(model);
        Map<String,String> keyMap = WebRsaUtils.getRSAData(customCacheChannel);
        model.addAttribute("keyMap",keyMap);
        return resultPage("/user/login/retrieve-page");
    }

    /**
     * 找回密码
     * @param mobile 手机号
     * @param mobileCode 手机验证码
     * @param password 新密码
     * @param confirmPwd 确认密码
     * @return Map<String, Object>
     */
    @RequestMapping("/ajax/retrievePassword")
    @ResponseBody
    public Map<String, Object> retrieveAjaxPassword(@RequestParam("mobile") String mobile,
                                                    @RequestParam("mobileCode") String mobileCode,
                                                    @RequestParam("password") String password,
                                                    @RequestParam("confirmPwd") String confirmPwd,
                                                    @RequestParam("sign") String sign) throws Exception{
        Map<String,Object> resultMap =  userLoginService.retrievePwd(mobile,mobileCode,password,confirmPwd,sign);
        if(!ResultUtil.getSuccess(resultMap)){
            Map<String,String> keyMap = WebRsaUtils.getRSAData(customCacheChannel);
            resultMap.put("keyMap",keyMap);
        }
        return  resultMap;
    }

    //=============================找回密码，结束================================

    /**
     * 手机发送验证码
     * @param mobile 手机号
     * @param status 类型，1注册，找回，3绑定，4更换，5完善资料
     * @param sessionId  完善资料时需要传入
     * @return Map<String ,Object>
     */
    @RequestMapping("/ajax/sendMobileMsg")
    @ResponseBody
    public Map<String, Object> sendMobileMsg(@RequestParam("mobile") String mobile,
                                             @RequestParam("status") int status,
                                             @RequestParam(value = "sessionId",required = false) String sessionId) {
        if(status!=1 && status!=2 && status!=5){
            return ResultUtil.ERROR("数据错误，短信发送失败");
        }
        return userSendSmsService.sendMobileCode(mobile,status,sessionId);
    }

    /**
     * 设置广告图片数据
     * @param model
     */
    private void setAdvertList(Model model){
        Map<String,Object> params = new HashMap<>();
        params.put("placeKey","LRBANNER");
        params.put("status", 1);
        List<Map<String, Object>> advertList = opAdvertService.queryAdvertList(params,false,false,false);//主页banner图片
        model.addAttribute("advertList",advertList);
    }

}
